exports = @
$ = jQuery

validationErrorCssClass = '.field-validation-error'
errorBoxCssClass = '.error-box'
fadeAwayAfter = 5 * 1000 # 5 Seconds

showError = (element, message) ->

    error = (element.siblings validationErrorCssClass).first()
    error.text message if message?
    error.hide().fadeIn 'normal', ->
        exports.setTimeout ->
            error.fadeOut 'normal'
        , fadeAwayAfter

hideError = (element) ->
    ($ element).siblings(validationErrorCssClass).first().fadeOut()

class FormController extends Spine.Controller

    @elements:  { 'form': 'form' }
    @events:    { 'submit form': 'submit' }

    constructor: ->

        super

        @hideErrors()

        @form.delegate "input, textarea, select, #{validationErrorCssClass}", 'vclick', (event) => hideError event.currentTarget

    activate: -> ($ 'input, textarea, select', @form).first()?.focus()

    reset: ->

        @hideErrors()
        @form.get(0).reset()

    showErrors: (errors) ->

        formErrors = []

        firstError = null

        for error in errors
            for message in error.messages
                if error.name is ''
                    formErrors.push message
                else
                    currentError = ($ "input[name=#{error.name}], textarea[name=#{error.name}], select[name=#{error.name}]", @form).first()
                    firstError = currentError unless firstError?
                    showError currentError, message

        $.mobile.silentScroll firstError.parent()
                                        .children(validationErrorCssClass)
                                        .offset()
                                        .top if firstError?

        unless formErrors.length then return 0

        if formErrors.length is 1
            html = "<p>#{formErrors[0]}</p>"
        else
            html = 'Please correct the following errors: <ol>'
            html += "<li>#{message}</li>" for message in formErrors
            html += '</ol>'

        ($ '.error-box', @form).remove()

        errorBox = $ "<div class='#{errorBoxCssClass} ui-body ui-corner-all 
                    ui-body-e'>#{html}</div>"

        errorBox.insertBefore($ 'div[data-role=fieldcontain]:last', @form)
                .fadeIn 'normal', ->
                    exports.setTimeout ->
                        errorBox.fadeOut 'normal', -> errorBox.remove()
                    , fadeAwayAfter

    hideErrors: ->

        ($ validationErrorCssClass, @form).hide()
        ($ errorBoxCssClass, @form).hide().remove()

exports.TomatoBreak.FormController = FormController